package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.async.AppNewsSolrAsync;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppNews;
import com.byit.enums.PromptInfo;
import com.byit.jgpush.JgPushExtra;
import com.byit.jgpush.JgPushService;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppNewsService;
import com.byit.service.IAppUserService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AnnouncementController
 * @Description 新闻资讯
 * @Author lxp
 * @Date 2019-01-02 11:32
 **/
@RestController
@RequestMapping("/api/sys/appNews")
public class AppNewsController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppNewsService appNewsService;
    @Autowired
    private AppNewsSolrAsync appNewsSolrAsync;

    @Autowired
    private JgPushService jgPushService;

    @Autowired
    private IAppUserService appUserService;

    /**
     * 新增或修改新闻资讯信息
     *
     * @param session
     * @param appNews
     * @return
     */
    @PostMapping("/add")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object insertAnnouncement(HttpSession session, AppNews appNews) {

        Long companyId = SessionHelper.getCompanyId(session);
        Long userId = SessionHelper.getUserId(session);
        try {
            Object x = validatorAppNews(appNews);

            if (x != null) return x;
            appNews.setCreateTime(new Date());
            appNews.setUpdateTime(new Date());
            //// 加密用户密码
            appNews.setOperationId(userId);
            appNews.setCompanyId(companyId);

            appNewsService.insertOrUpdate(appNews);
            //同步solr
            appNewsSolrAsync.save(appNews);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 校验新闻
     * @param appNews
     * @return
     */
    private Object validatorAppNews(AppNews appNews) {
        if (null == appNews) {
            return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
        }
        if (appNews.getContent() == null || appNews.getContent().length() < 100) {
            return MessageResult.warpper("001", null, "内容不少于100字符");
        }
        if (appNews.getTitle() == null ) {
            return MessageResult.warpper("001", null, "标题不能为空!!");
        }
        if ( appNews.getTitle().length() > 100) {
            return MessageResult.warpper("001", null, "标题不能超过100字符");
        }
        return null;
    }

    /**
     * 新增或修改新闻资讯信息
     *
     * @param session
     * @param appNews
     * @return
     */
    @PostMapping("/edit")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object update(HttpSession session, AppNews appNews) {

        Long companyId = SessionHelper.getCompanyId(session);
        Long userId = SessionHelper.getUserId(session);
        //校验
        if (appNewsService.selectById(appNews.getId()).getPublish()==1) {
            return MessageResult.error("已经审核,无法编辑");
        }
        try {

            if (appNews.getContent() == null || appNews.getContent().length() < 100) {
                return MessageResult.warpper("001", null, "内容不少于100字符");
            }
            //// 加密用户密码
            appNews.setOperationId(userId);
            appNews.setCompanyId(companyId);

            appNewsService.insertOrUpdate(appNews);
            //同步solr
            appNewsSolrAsync.save(appNews);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 通过Id查询新闻资讯
     *
     * @param id
     * @return
     */
    @GetMapping("/details")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppNewsById(@RequestParam("id") Integer id) {
        AppNews appNews = appNewsService.selectById(id);
       /* String searchMinio = appNewsService.getSearchMinio();
        appNews.setPicture(searchMinio + appNews.getPicture());*/
        return MessageResult.success(appNews);
    }

    /**
     * 按照条件查询新闻资讯
     *
     * @param session
     * @param title
     * @param level
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("/list")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppNewsAll(HttpSession session,
                                   @RequestParam(value = "title", defaultValue = "") String title,
                                   @RequestParam(value = "level", defaultValue = "") String level,
                                   @RequestParam(value = "type", defaultValue = "") String type,
                                   @RequestParam(value = "source", defaultValue = "") String source,
                                   @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                   @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppNews> pageInfo = new Page<>(page, limit);
        //新闻权限控制
        Long companyId = SessionHelper.getCompanyId(session);
        //超级管理员
        if (companyId == 1) {
            companyId = null;
        }
        Map<String, Object> params = MapBuilder.newMap(5).setParam("level", level)
                .setParam("type", type)
                .setParam("companyId", companyId)
                .setParam("source", source).ok();
        if (null != title && !"".equals(title)) {
            params.put("title", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(title) + "%");
        }
        Page<JSONObject> result = appNewsService.selectAppnewsAll(pageInfo, params);

        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除新闻资讯信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/del")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    public Object delAppNewsByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {

            map.put("id", id);
            appNewsService.delAppnewsById(map);
        }
        //同步solr
        appNewsSolrAsync.del(ids);
        return MessageResult.success();
    }


    /**
     * 上传图片
     */
    @PostMapping("/upload")
    @Log(title = "新闻资讯", operate = OperatorType.IMG_UPLOAD, channel = ChannelType.WEB_INTER)
    public Object upload(@RequestParam("file") MultipartFile file) {

        String path = appNewsService.getPictrePath(file, "appNews");
        try {
            if (null == path) {
                return MessageResult.error("文件不能为空");
            } else {
                return MessageResult.success(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }


    }

    /**
     * 获取新闻类型
     */
    @GetMapping("/types")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object getNewsType(HttpSession session,
                              @RequestParam(value = "type", defaultValue = "") String type) {

        List<JSONObject> appNewsTypes = appNewsService.getAppNewsType(type);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, appNewsTypes);
    }

    /**
     * 新闻发布
     *
     * @param id
     * @return
     */
    @PostMapping("/publish")
    @Log(title = "新闻资讯", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object publishAppNews(@RequestParam("id") Long id,
                                 @RequestParam("publish") Integer publish,
                                 @RequestParam(value = "pushType", defaultValue = "")String pushType) {


        AppNews appNews = appNewsService.selectById(id);

        //校验
        if (appNews.getPublish()==1) {
            return MessageResult.error("请勿重复审核");
        }
        appNews.setId(id);
        appNews.setPublish(publish);
        try {

            boolean b = appNewsService.updateById(appNews);

            if (b) {
                //选择了推送
                if (appNews.getIsPush()==1) {
                    if (publish == 1) {
                        //推送
                        /**
                         * 类型 接收类型 0 推送 1短信 2一起',
                         */
                        JSONObject param = new JSONObject();

                        param.put("msg", appNews.getMsg());
                        param.put("title", appNews.getTitle());
                        /**
                         * 自定义内容
                         */
                        JgPushExtra extra = new JgPushExtra();
                        /**/
                        extra.setType(4);
                        extra.setLevel(2);
                        // extra.setContent(appNews.getContent());
                        extra.setTitle("新闻通知");
                        extra.setTime(new Date());
                        extra.setSource("智慧江油");
                        param.put("data", extra);
                        try {
                            jgPushService.jpushAllByAndroidIOS(param);
                        } catch (Exception e) {
                            return MessageResult.error(e.getMessage());
                        }
//                        if (pushType.equals("0")) {
//
//                            /*全部推送*/
//                            jgPushService.jpushAllByAndroidIOS(param);
//
//                        } else if (pushType.equals("1")) {
//                            /*发短信*/
//                            /*查询所有手机用户*/
////                        EntityWrapper<AppUser> wrapper = new EntityWrapper<>();
////                        wrapper.setSqlSelect("id,device_id,url");
////                        wrapper.eq("is_del", 0);
////                            List<JSONObject> phoneList = appUserService.selectAllUserPhone();
////                            for (JSONObject phone : phoneList) {
////                                SendMessService.sendSms(appNews.getMsg(), phone.toString());
////                            }
//
//                        } else if (pushType.equals("2")) {
//                            /*推送 ,短信一起*/
//                           /* List<JSONObject> phoneList = appUserService.selectAllUserPhone();
//                            for (JSONObject phone : phoneList) {
//                                *//*短信*//*
//                                SendMessService.sendSms(appNews.getMsg(), phone.toString());
//                            }*/
//                            /*推送*/
//                            jgPushService.jpushAllByAndroidIOS(param);
//
//
//                        }


                    }
                }

            }
        } catch (Exception e) {
            return MessageResult.error(e.getMessage());
        }
        return MessageResult.success();
    }
}
